package list;

public class leetcode21 {
    public static void main(String[] args) {
        int[] nums1 = {1,2,4};
        int[] nums2 = {1,3,4};
        ListNode head1 = createListNode(nums1);
        ListNode head2 = createListNode(nums2);
        System.out.println("head1:");
        printList(head1);
        System.out.println("head2:");
        printList(head2);
        ListNode head = mergeTwoLists(head1, head2);
        System.out.println("mergehead:");
        printList(head);
    }

    private static ListNode createListNode(int[] nums){
        ListNode head = new ListNode(nums[0]);
        ListNode current = head;
        for (int i = 1; i < nums.length; i++) {
            ListNode temp = new ListNode(nums[i]);
            current.next = temp;
            current = current.next;
        }
        return head;
    }

    public static void printList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " -> ");
            head = head.next;
        }
        System.out.println("null");
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null && list2 == null) return null;
        if(list1 == null) return list2;
        if(list2 == null) return list1;
        ListNode head = new ListNode(0);
        ListNode cur = head;
        while(list1 != null && list2 != null){
            if(list1.val < list2.val){
                cur.next = list1;
                list1 = list1.next;
                cur = cur.next;
            }
            else{
                cur.next = list2;
                list2 = list2.next;
                cur = cur.next;
            }
        }

        if(list1 == null){
            cur.next = list2;
        }
        else{
            cur.next = list1;
        }

        return head.next;
    }
}
